﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using HKEA.CMS.Core.BLL;
using HKEA.CMS.Core.Models;
using HKEA.CMS.Core.Utility;
using HKEA.CMS.Core.BLL.Tbl;
using HKEA.CMS.Core.BLL.App;
using HKEA.CMS.Core.BLL.Mtbl;
using System.Transactions;

namespace WebApplication
{
    public partial class M_Businessnature : BasePage
    {
        //private int customeruid = 0;
        static int customeruid;
        #region 初始化 tblCust_BusNature ,app_tblCust_BusNature ,mtblBusinessNature
        tblCust_BusNature cust_busNatureENT = new tblCust_BusNature();
        tblCust_BusNatureBLL cust_busNatureBLL = new tblCust_BusNatureBLL();
        app_tblCust_BusNature app_cust_busNatureENT ;
        app_tblCust_BusNatureBLL app_cust_busNatureBLL = new app_tblCust_BusNatureBLL();
        mtblBusinessNature busNatureENT = new mtblBusinessNature();
        mtblBusinessNatureBLL busNatureBLL = new mtblBusinessNatureBLL();
        List<app_tblCust_BusNature> listAppCustBusNture = new List<app_tblCust_BusNature>();
        static List<tblCust_BusNature>  listCustBusNture = new List<tblCust_BusNature>();
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            app_cust_busNatureENT = new app_tblCust_BusNature();
            if (!IsPostBack)
            {
                BindNatureList();
                if (GetEnt()>0)
                {
                    customeruid = GetEnt();
                    //customeruid = Convert.ToInt32(Request.QueryString[Constant.UrlParamName.CustomerUID]);
                    app_cust_busNatureENT.CustomerUID = customeruid;
                    cust_busNatureENT.CustomerUID = customeruid;
                    listAppCustBusNture = app_cust_busNatureBLL.GetListByENT(app_cust_busNatureENT, true);
                    listCustBusNture = cust_busNatureBLL.GetListByENT(cust_busNatureENT, true);

                    if (customeruid>0)
                    {
                        SetCustomerNature();
                    }
                    else
                    {
                        SetNoOption();
                    }
                }
                else
                {
                    SetNoOption();
                    usermeg.Visible = false;
                    lblMeg.Text = ResourceManage.GetResourceString("msg200002");
                }
            }
        }
        /// <summary>
        /// 绑定Customer已经有的信息
        /// </summary>
        protected void SetCustomerNature()
        {
            app_cust_busNatureENT = new app_tblCust_BusNature();
            if (customeruid > 0)
            {
                if (CheckEnt() == true)
                {
                    #region 分别取出app_tblCust_BusNature表中的数据,以及tblCust_BusNature表中的数据

                    app_cust_busNatureENT.CustomerUID = customeruid;
                    app_cust_busNatureENT.Deleted = 0;
                    var appCustBusNaturelist = app_cust_busNatureBLL.GetListByENT(app_cust_busNatureENT, false).ToList();

                    cust_busNatureENT.Deleted = 0;
                    cust_busNatureENT.CustomerUID = customeruid;
                    var custBusNaturelist = cust_busNatureBLL.GetListByENT(cust_busNatureENT, true).ToList();

                    #endregion

                    List<int> tempList=new List<int>();
                    for (int i = 0; i < custBusNaturelist.Count(); i++)
                    {
                        int Count = appCustBusNaturelist.Where(a => a.BusNatureUID == custBusNaturelist[i].BusNatureUID).Count();
                        if (Count == 0) {
                            tempList.Add(custBusNaturelist[i].BusNatureUID);
                        }
                    }
                    foreach (app_tblCust_BusNature item in appCustBusNaturelist)
                    {
                        if (item.Deleted == 0)
                        {
                            int temp = item.BusNatureUID;
                            tempList.Add(temp);
                        }
                    }

                    if (tempList.Count > 0) {
                        foreach(int item in tempList){
                        for (int i = 0; i < ckbNatureList.Items.Count; i++) {
                            if (ckbNatureList.Items[i].Value == item.ToString())
                            {
                                ckbNatureList.Items[i].Selected = true;
                                HiddenField_val.Value += ckbNatureList.Items[i].Value + ",";
                                break;
                            }
                            }
                        }
                    }
                    #region 
                    //string strbusNatureUID = string.Empty;

                    //if (appCustBusNaturelist.Count > 0)
                    //{
                    //    foreach (var tempENT in appCustBusNaturelist)
                    //    {
                    //        for (int i = 0; i < ckbNatureList.Items.Count; i++)
                    //        {
                    //            if (ckbNatureList.Items[i].Value == tempENT.BusNatureUID.ToString())
                    //            {
                    //                ckbNatureList.Items[i].Selected = true;
                    //                break;
                    //            }
                    //        }
                    //    }
                    //    hidStrNatureUID.Value = strbusNatureUID;
                    //}
                    //else
                    //{
                    //    foreach (var tempENT in custBusNaturelist)
                    //    {
                    //        for (int i = 0; i < ckbNatureList.Items.Count; i++)
                    //        {
                    //            if (ckbNatureList.Items[i].Value == tempENT.BusNatureUID.ToString())
                    //            {
                    //                UpDateTbltoApp(tempENT);
                    //                ckbNatureList.Items[i].Selected = true;
                                    
                    //                break;
                    //            }
                    //        }
                    //    }
                    //    hidStrNatureUID.Value = strbusNatureUID;
                    //}
                    #endregion
                }
                else
                {
                    lblMeg.Text = ResourceManage.GetResourceString("msg200014");
                }
            }
        }

        private void SetNoOption()
        {
            lkBtnSave.Enabled = false;
            lblMeg.Text = ResourceManage.GetResourceString("msg200001");
        }
        /// <summary>
        /// 绑定选中的数据
        /// </summary>
        protected void BindNatureList()
        {
            busNatureENT.Deleted = 0;
            var list = busNatureBLL.GetListByENT(busNatureENT);
            for (int i = 0; i < list.Count; i++)
                list[i].LastModifyBy = list[i].BusNature_Eng + " " + list[i].BusNature_Chi;
            ckbNatureList.DataSource = list;
            ckbNatureList.DataTextField = "LastModifyBy";
            ckbNatureList.DataValueField = "BusNatureUID";
            ckbNatureList.DataBind();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            lblMeg.Text = "";

            app_cust_busNatureENT = new app_tblCust_BusNature();
            #region 保存方案
            //1:如果app_tblCust_BusNature没有包含当前Customer的修改数据,当用户修改后获取当前勾选的数据新增到App_MainMarket表中
            //2:如果app_tblCust_BusNature已经有Customer的数据存在,则在分3个步骤 
            //2-> 1)对比当前勾选是否已经存在,若存在,并且Deleted=0,从源表中获取数据添加到Save方法  2)如果没有,表示新数据,作为新纪录添加到Save方法 3)表中存在,但是当前没有勾选,记录到unselectd中;
            #endregion
            #region 计算app_tblCust_BusNature是否包含Customer数据
            List<app_tblCust_BusNature> temApplist = new List<app_tblCust_BusNature>();
            app_cust_busNatureENT.CustomerUID = customeruid;
            var tmpAppList = app_cust_busNatureBLL.GetListByENT(app_cust_busNatureENT, true).Select(a => a.BusNatureUID).ToList();
            #endregion

            if (GetEnt()>0)
            {             
                if (CheckEnt()== true)
                {
                    lblMeg.Text = ResourceManage.GetResourceString("msg400003");
                    List<int> unselectd_uid = new List<int>();                   
                    for (int i = 0; i < ckbNatureList.Items.Count; i++)
                    {
                        if (ckbNatureList.Items[i].Selected) //获取勾选的数据
                        {
                            app_cust_busNatureENT = new app_tblCust_BusNature();
                            int item = Convert.ToInt32(ckbNatureList.Items[i].Value);
                            var resuleTbl = listCustBusNture.Where(a => a.CustomerUID == customeruid && a.BusNatureUID==item).ToList();
                            var resuleApp = listAppCustBusNture.Where(a => a.CustomerUID == customeruid && a.BusNatureUID==item).ToList();

                            #region
                            if (resuleApp.Count() > 0) {
                                foreach (app_tblCust_BusNature C in resuleApp) {
                                    app_cust_busNatureENT.Cust_BusNatureUID = C.Cust_BusNatureUID;
                                    app_cust_busNatureENT.CustomerUID = C.CustomerUID;
                                    app_cust_busNatureENT.BusNatureUID = C.BusNatureUID;
                                    app_cust_busNatureENT.Deleted = Constant.IsDelete.no;
                                }
                            }
                            else if(resuleApp.Count()==0&&resuleTbl.Count()>0)
                            {
                                foreach (tblCust_BusNature C in resuleTbl)
                                {
                                    app_cust_busNatureENT.Cust_BusNatureUID = C.Cust_BusNatureUID;
                                    app_cust_busNatureENT.CustomerUID = C.CustomerUID;
                                    app_cust_busNatureENT.BusNatureUID = C.BusNatureUID;
                                    app_cust_busNatureENT.Deleted = Constant.IsDelete.no;
                                }
                            }
                            else //新增数据 2->2)
                            {
                                app_cust_busNatureENT.Cust_BusNatureUID = 0;
                                app_cust_busNatureENT.CustomerUID = customeruid;
                                app_cust_busNatureENT.BusNatureUID = item;
                                app_cust_busNatureENT.Deleted = Constant.IsDelete.no;
                            }
                            temApplist.Add(app_cust_busNatureENT);
                            #endregion
                        }
                        else //删除的数据
                        {
                            int item = Convert.ToInt32(ckbNatureList.Items[i].Value);
                            int tmptbl = listCustBusNture.Where(a=>a.BusNatureUID==item).Count();
                            int tmpApp = tmpAppList.Where(a => a == item).Count();
                            if (tmptbl > 0 |tmpApp>0)
                            {
                                unselectd_uid.Add(item);
                            }
                        }
                    }
                    TransactionOptions sptions = new TransactionOptions();
                    sptions.Timeout = new TimeSpan(0,5,0);
                    sptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
                    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, sptions))
                    {
                        _save(temApplist, customeruid);
                        _delete(unselectd_uid, customeruid);
                        WriteToLog();
                        try
                        {
                            scope.Complete();
                            lblMeg.Text = ResourceManage.GetResourceString("msg200004");
                        }
                        catch (Exception ex)
                        {
                            lblMeg.Text = ResourceManage.GetResourceString("msg200003");
                        }
                    }
                }
                else
                {
                    SetNoOption();
                    lblMeg.Text = ResourceManage.GetResourceString("msg200014");
                }
            }
            else
            {
                lkBtnSave.Enabled = false;
                lblMeg.Text = ResourceManage.GetResourceString("msg400004");
            }
        }

        private void _save(List<app_tblCust_BusNature> listBusNature, int custUID)
        {
            #region
            List<app_tblCust_BusNature> tmpApplist = new List<app_tblCust_BusNature>();
            app_cust_busNatureENT = new app_tblCust_BusNature();
            app_cust_busNatureENT.CustomerUID = custUID;
            app_cust_busNatureENT.Deleted = -1;
            tmpApplist = app_cust_busNatureBLL.GetListByENT(app_cust_busNatureENT, false);
            List<tblCust_BusNature> tmpTbllist = new List<tblCust_BusNature>();
            cust_busNatureENT.CustomerUID = custUID;
            cust_busNatureENT.Deleted = 0;
            tmpTbllist = cust_busNatureBLL.GetListByENT(cust_busNatureENT, true);
            #endregion

            for (int i = 0; i < listBusNature.Count(); i++)
            {
                int App_tal = tmpApplist.Where(a => a.BusNatureUID == listBusNature[i].BusNatureUID).Count();
                int tbl_tal = tmpTbllist.Where(a => a.BusNatureUID == listBusNature[i].BusNatureUID).Count();

                if (App_tal <= 0 && tbl_tal<=0)
                {
                    listBusNature[i].Deleted = Constant.IsDelete.no;
                    AddItem(listBusNature[i] as app_tblCust_BusNature, custUID);
                }
                else if (App_tal== 1)
                    {
                        var val = tmpApplist.Where(a => a.BusNatureUID == listBusNature[i].BusNatureUID).ToList();
                        // App_中有对应的数据,表示当前这条数据并不需要更改,所以把原来在App_中临时的数据取消更改,需要删除App_对应的数据
                        int tamp = val.Where(a => a.Deleted == Constant.IsDelete.yes).Count();
                        if (tamp == 1)
                        {
                            DeleteItem(listBusNature[i] as app_tblCust_BusNature, custUID);
                            //UpdateItem(listCountry[i] as app_tblCust_BusNature, custUID);
                        }
                }
            }
        }
        private void _delete(List<int> listBusnature, int custUID)
        {
            #region 初始化App 和Tbl的数据
            app_cust_busNatureENT = new app_tblCust_BusNature();
            List<app_tblCust_BusNature> ApptempList=app_cust_busNatureBLL.GetListByENT(app_cust_busNatureENT,false);
            List<tblCust_BusNature> tmpTbllist = new List<tblCust_BusNature>();
            cust_busNatureENT.CustomerUID = custUID;
            cust_busNatureENT.Deleted = 0;
            tmpTbllist = cust_busNatureBLL.GetListByENT(cust_busNatureENT, true);
            #endregion

            for (int i = 0; i < listBusnature.Count(); i++)
            {
                #region 初始化需要删除的对象实体->app_cust_busNatureENT
                app_cust_busNatureENT = new app_tblCust_BusNature();
                app_cust_busNatureENT.CustomerUID = customeruid;
                app_cust_busNatureENT.BusNatureUID = listBusnature[i];
                #endregion
                int App_tal = ApptempList.Where(a => a.BusNatureUID == listBusnature[i]).Count();
                int Tbl_tal = tmpTbllist.Where(a => a.BusNatureUID == listBusnature[i]).Count();
                if (App_tal == 1 && Tbl_tal == 0)
                {
                    DeleteItem(app_cust_busNatureENT, custUID);
                }
                else if(App_tal==0&&Tbl_tal==1){
                    var items=tmpTbllist.Where(a => a.BusNatureUID == listBusnature[i]).ToList();
                    foreach (tblCust_BusNature item in items)
                    {
                        app_cust_busNatureENT.Cust_BusNatureUID = item.Cust_BusNatureUID;
                        app_cust_busNatureENT.Deleted = Constant.IsDelete.yes;
                        AddItem(app_cust_busNatureENT, custUID);
                    }
                }
                #region
                //foreach (app_tblCust_BusNature item in ApptempList)
                //{
                //    app_cust_busNatureENT.Deleted = Constant.IsDelete.yes;
                //    UpdateItem(item, customeruid);
                //};
                #endregion
            }
        }
        /// <summary>
        /// 校验CustomerUID是否存在
        /// </summary>
        /// <returns></returns>
        bool CheckEnt() {
            bool ret = true;
            tblCustomer customerENT = new tblCustomer();
            tblCustomerBLL customerBLL = new tblCustomerBLL();
            customerENT.Deleted = 0;
            customerENT.CustomerUID = GetEnt();
            try
            {
                var tempENT = customerBLL.GetEntity(customerENT);
                if (tempENT == null)
                {
                    ret = false;
                }
            }
            catch (Exception ex) {
                ret = false;
            }
            return ret;
        }

        /// <summary>
        /// 将TblCust_BusNature更新到App_TblCust_BusNature
        /// </summary>
        /// <param name="ent"></param>
        void UpDateTbltoApp(tblCust_BusNature ent) {
            app_cust_busNatureENT = new app_tblCust_BusNature();
            app_cust_busNatureENT.CustomerUID = customeruid;
            app_cust_busNatureENT.Cust_BusNatureUID = ent.Cust_BusNatureUID;
            app_cust_busNatureENT.Remark = ent.Remark;
            app_cust_busNatureENT.Deleted = ent.Deleted;
            app_cust_busNatureENT.BusNatureUID = ent.BusNatureUID;
            app_cust_busNatureENT.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
            app_cust_busNatureBLL.InsertENT(app_cust_busNatureENT);
        }

        /// <summary>
        /// member修改了记录,临时记录将会添加到App_表中
        /// </summary>
        /// <param name="item"></param>
        /// <param name="Cuid"></param>
        void AddItem(app_tblCust_BusNature item,int Cuid ) {
            app_cust_busNatureENT = new app_tblCust_BusNature();
            app_cust_busNatureENT.Cust_BusNatureUID = item.Cust_BusNatureUID;
            app_cust_busNatureENT.BusNatureUID = item.BusNatureUID;
            app_cust_busNatureENT.CustomerUID = item.CustomerUID;
            app_cust_busNatureENT.Deleted = item.Deleted;
            app_cust_busNatureENT.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
            app_cust_busNatureBLL.InsertENT(app_cust_busNatureENT);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        /// <param name="Cuid"></param>
        void UpdateItem(app_tblCust_BusNature item,int Cuid) {
            app_cust_busNatureENT = new app_tblCust_BusNature();
            app_cust_busNatureENT.CustomerUID = Cuid;
            app_cust_busNatureENT.BusNatureUID = item.BusNatureUID;
            app_cust_busNatureENT.Deleted = item.Deleted;
            app_cust_busNatureENT.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
            app_cust_busNatureBLL.UpdateENT(app_cust_busNatureENT);
        }

        /// <summary>
        /// 删除临时表的记录
        /// </summary>
        /// <param name="item"></param>
        /// <param name="Cuid"></param>
        void DeleteItem(app_tblCust_BusNature item, int Cuid) {
            app_cust_busNatureENT.CustomerUID = Cuid;
            app_cust_busNatureENT.AppCust_BusNatureUID = item.AppCust_BusNatureUID;
            app_cust_busNatureENT.BusNatureUID = item.BusNatureUID;
            app_cust_busNatureBLL.DeleteENT(app_cust_busNatureENT);
        }

        protected void LbtnQuit_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/M_Businessnature.aspx");
        }

        protected void WriteToLog()
        {
            string LoginName = tblCust_WebLoginBLL.GetInstance().GetENT(GetMemberLoginUID()).LoginName.ToString();
            string addlog = string.Empty;
            string dellog = string.Empty;
            mtblBusinessNature entBN = new mtblBusinessNature();
            List<mtblBusinessNature> list = mtblBusinessNatureBLL.GetInstance().GetListByENT(entBN);
            string[] add = HiddenFiled_add.Value.Split(',');
            string[] delete = HiddenFiled_del.Value.Split(',');
            if (add.Length > 1 | delete.Length > 1)
            {
                for (int i = 0; i < add.Length - 1; i++) {
                    var result = list.Where(a => a.BusNatureUID == Convert.ToInt32(add[i])).Select(p => p).ToList();
                    foreach(mtblBusinessNature item in result){
                        addlog += item.BusNature_Eng + ",";
                    }
                }
                for (int i = 0; i < delete.Length - 1; i++) {
                    var result = list.Where(a=>a.BusNatureUID==Convert.ToInt32(delete[i])).Select(p=>p).ToList();
                    foreach (mtblBusinessNature item in result) {
                        dellog += item.BusNature_Eng + ",";
                    }
                }
                if (addlog.Length > 1)
                    addlog = " Add " + addlog.Substring(0, addlog.Length - 1);
                else
                    addlog = "";
                if (dellog.Length > 1)
                    dellog = " Delete " + dellog.Substring(0, dellog.Length - 1);
                else
                    dellog = "";

                tblHistory entlog = new tblHistory();
                Literal CompanyName = usermeg.FindControl("ltlCompanyName_eng") as Literal;
                entlog.HistoryCatUID = 2;
                entlog.HistoryTypeUID = 8;
                entlog.CustomerUID = GetEnt();
                entlog.Cust_MemberUID = 0;
                entlog.ContactPersonUID = 0;
                entlog.History_Detail = LoginName + " {"+CompanyName.Text+"}{BusinessNature}" + addlog + dellog;
                entlog.LastModifyBy = LoginName;
                int tal = tblHistoryBLL.GetInstance().InsertENT(entlog);
            }
        }
    }
}